import asyncio
import logging
import json
import uuid
import argparse
from datetime import datetime
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from contextlib import asynccontextmanager

from config import settings
from websocket_server import ws_server
from workflow_manager import workflow_manager, periodic_cleanup
from data_sources import data_source_service
from agents import get_available_agents, AGENT_REGISTRY
import uvicorn

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler('app.log', encoding='utf-8')
    ]
)

logger = logging.getLogger(__name__)

# 后台任务
background_tasks = []

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时
    logger.info("启动后台任务...")
    
    # 启动定期清理任务
    cleanup_task = asyncio.create_task(periodic_cleanup())
    background_tasks.append(cleanup_task)
    
    logger.info("后台任务已启动")
    
    yield
    
    # 关闭时
    logger.info("停止后台任务...")
    for task in background_tasks:
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            pass
    logger.info("后台任务已停止")

# 创建FastAPI应用
app = FastAPI(
    title="小U智能助手 Demo",
    description="基于LangGraph和WebSocket的智能助手演示系统",
    version="1.0.0",
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/", response_class=HTMLResponse)
async def get_index():
    """返回测试页面"""
    html_content = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小U智能助手 Demo</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            width: 95%;
            max-width: 1200px;
            height: 95vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 24px;
            margin-bottom: 8px;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 14px;
        }
        
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 20px;
            min-height: 0;
            height: calc(100% - 120px);
        }
        
        .messages {
            flex: 1;
            overflow-y: auto;
            border: 1px solid #e1e5e9;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
            background: #f8f9fa;
            min-height: 300px;
            max-height: calc(100vh - 400px);
        }
        
        .message {
            margin-bottom: 15px;
            padding: 12px 16px;
            border-radius: 12px;
            max-width: 80%;
            word-wrap: break-word;
        }
        
        .message.user {
            background: #007bff;
            color: white;
            margin-left: auto;
            text-align: right;
        }
        
        .message.assistant {
            background: #e9ecef;
            color: #333;
        }
        
        .message.confirmation {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
            align-self: flex-start;
            border-radius: 8px;
        }
        
        .confirmation-options {
            margin-top: 10px;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .confirmation-option {
            padding: 8px 12px;
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .confirmation-option:hover {
            background: #f8f9fa;
            border-color: #007bff;
        }
        
        .workflow-status {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            color: #1565c0;
            padding: 10px;
            border-radius: 6px;
            margin: 5px 0;
            font-size: 14px;
        }
        
        .agent-step {
            background: #f3e5f5;
            border-left: 4px solid #9c27b0;
            padding: 8px 12px;
            margin: 5px 0;
            border-radius: 0 4px 4px 0;
        }
        
        .message.system {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
            text-align: center;
            font-size: 14px;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .message.streaming {
            position: relative;
        }
        
        .message.streaming::after {
            content: '▋';
            animation: blink 1s infinite;
            color: #007bff;
        }
        
        @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0; }
        }
        
        .message-content {
            display: inline;
        }
        
        .input-container {
            display: flex;
            gap: 10px;
            position: sticky;
            bottom: 0;
            background: white;
            padding: 10px 0;
            border-top: 1px solid #e1e5e9;
            margin-top: auto;
        }
        
        .input-container input {
            flex: 1;
            padding: 12px 16px;
            border: 2px solid #e1e5e9;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.3s;
        }
        
        .input-container input:focus {
            border-color: #007bff;
        }
        
        .input-container button {
            padding: 12px 24px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        
        .input-container button:hover {
            background: #0056b3;
        }
        
        .input-container button:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }
        
        .status {
            padding: 8px 16px;
            margin-bottom: 10px;
            border-radius: 8px;
            font-size: 12px;
            text-align: center;
        }
        
        .status.connected {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status.disconnected {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .skills-panel {
            margin-bottom: 15px;
            padding: 12px;
            background: #f8f9fa;
            border-radius: 12px;
            border: 1px solid #e1e5e9;
            max-height: 200px;
            overflow-y: auto;
        }
        
        .skills-title {
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #495057;
        }
        
        .skills-list {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 8px;
        }
        
        .skill-button {
            padding: 12px 16px;
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.3s;
            position: relative;
            text-align: left;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            min-height: 60px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }
        
        .skill-button:hover {
            background: #007bff;
            color: white;
            border-color: #007bff;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,123,255,0.3);
        }
        
        .skill-button.selected {
            background: #007bff;
            color: white;
            border-color: #0056b3;
            box-shadow: 0 4px 8px rgba(0,123,255,0.4);
        }
        
        .skill-examples {
            font-size: 11px;
            color: #495057;
            margin-top: 4px;
            font-style: italic;
            line-height: 1.3;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .skill-button:hover .skill-examples,
        .skill-button.selected .skill-examples {
            color: rgba(255,255,255,0.8);
        }
        
        .example-link {
            text-decoration: underline;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .example-link:hover {
            font-weight: bold;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                width: 100%;
                height: 100vh;
                border-radius: 0;
            }
            
            .chat-container {
                padding: 15px;
            }
            
            .skills-list {
                grid-template-columns: 1fr;
                gap: 6px;
            }
            
            .skill-button {
                min-height: 50px;
                padding: 10px 12px;
                font-size: 12px;
            }
            
            .skill-examples {
                font-size: 10px;
            }
            
            .messages {
                min-height: 250px;
                max-height: calc(100vh - 350px);
            }
            
            .input-container input {
                font-size: 16px; /* 防止iOS缩放 */
            }
        }
        
        @media (max-width: 480px) {
            .header h1 {
                font-size: 20px;
            }
            
            .header p {
                font-size: 12px;
            }
            
            .skills-panel {
                padding: 8px;
                max-height: 150px;
            }
            
            .messages {
                padding: 10px;
                max-height: calc(100vh - 320px);
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 小U智能助手</h1>
            <p>基于LangGraph和WebSocket的智能助手演示系统</p>
        </div>
        
        <div class="chat-container">
            <div id="status" class="status disconnected">正在连接...</div>
            
            <div class="skills-panel">
                <div class="skills-title">选择技能 (点击查看示例):</div>
                <div id="skillsList" class="skills-list">
                    <div class="skill-button" onclick="selectSkill('global')" title="查找用户信息、部门架构、组织关系等">
                        👥 全局查询
                        <div class="skill-examples">
                            示例: 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('global', '查找张三的联系方式')">查找张三的联系方式</span> | 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('global', '技术部有哪些员工？')">技术部有哪些员工？</span> | 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('global', '显示公司组织架构')">显示公司组织架构</span>
                        </div>
                    </div>
                    <div class="skill-button" onclick="selectSkill('knowledge')" title="基于知识库回答政策、流程、规章制度等问题">
                        📚 知识问答
                        <div class="skill-examples">
                            示例: 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('knowledge', '公司的请假政策是什么？')">公司的请假政策是什么？</span> | 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('knowledge', '如何申请出差报销？')">如何申请出差报销？</span> | 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('knowledge', '新员工入职流程')">新员工入职流程</span>
                        </div>
                    </div>
                    <div class="skill-button" onclick="selectSkill('data_analysis')" title="分析生产数据、销售数据，生成图表报告">
                        📊 数据分析
                        <div class="skill-examples">
                            示例: 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('data_analysis', '显示今天的生产数据')">显示今天的生产数据</span> | 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('data_analysis', '分析本月销售趋势')">分析本月销售趋势</span> | 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('data_analysis', '生成设备运行报告')">生成设备运行报告</span>
                        </div>
                    </div>
                    <div class="skill-button" onclick="selectSkill('form')" title="创建各种表单、申请单、预订单等">
                        📝 表单创建
                        <div class="skill-examples">
                            示例: 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('form', '我要预订会议室')">我要预订会议室</span> | 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('form', '创建请假申请表')">创建请假申请表</span> | 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('form', '申请设备维修')">申请设备维修</span>
                        </div>
                    </div>
                    <div class="skill-button" onclick="selectSkill('general_chat')" title="通用对话、闲聊、问答等">
                        💬 通用对话
                        <div class="skill-examples">
                            示例: 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('general_chat', '今天天气怎么样？')">今天天气怎么样？</span> | 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('general_chat', '帮我写一份工作总结')">帮我写一份工作总结</span> | 
                            <span class="example-link" onclick="event.stopPropagation(); tryExample('general_chat', '推荐一些学习资料')">推荐一些学习资料</span>
                        </div>
                    </div>
                </div>
                
                <div class="multi-agent-examples" style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #007bff;">
                    <div style="font-weight: bold; color: #007bff; margin-bottom: 8px;">🚀 多Agent协作示例:</div>
                    <div style="font-size: 12px; line-height: 1.4;">
                        <span class="example-link" onclick="tryExample('', '查找张三的信息并为他创建请假申请表')">查找张三的信息并为他创建请假申请表</span> | 
                        <span class="example-link" onclick="tryExample('', '分析销售数据并生成报告表单')">分析销售数据并生成报告表单</span> | 
                        <span class="example-link" onclick="tryExample('', '查询请假政策并帮我申请明天的假期')">查询请假政策并帮我申请明天的假期</span>
                    </div>
                </div>
            </div>
            
            <div id="messages" class="messages">
                <div class="message system">欢迎使用小U智能助手！请选择技能或直接输入问题。</div>
            </div>
            
            <div class="input-container">
                <input type="text" id="messageInput" placeholder="请输入您的问题..." onkeypress="handleKeyPress(event)">
                <button onclick="sendMessage()" id="sendButton">发送</button>
            </div>
        </div>
    </div>

    <script>
        let ws = null;
        let isConnected = false;
        
        function connect() {
            const wsUrl = `ws://localhost:8000/ws`;
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function(event) {
                isConnected = true;
                updateStatus('connected', '已连接到服务器');
                console.log('WebSocket连接已建立');
            };
            
            ws.onmessage = function(event) {
                try {
                    const message = JSON.parse(event.data);
                    handleMessage(message);
                } catch (error) {
                    console.error('解析消息失败:', error);
                }
            };
            
            ws.onclose = function(event) {
                isConnected = false;
                updateStatus('disconnected', '连接已断开');
                console.log('WebSocket连接已关闭');
                
                // 尝试重连
                setTimeout(connect, 3000);
            };
            
            ws.onerror = function(error) {
                console.error('WebSocket错误:', error);
                updateStatus('disconnected', '连接错误');
            };
        }
        
        function updateStatus(status, message) {
            const statusElement = document.getElementById('status');
            statusElement.className = `status ${status}`;
            statusElement.textContent = message;
        }
        
        let currentStreamingMessage = null;
        
        function addMessage(content, type = 'assistant', isStreaming = false, data = null) {
            const messagesDiv = document.getElementById('messages');
            
            // 处理流式消息
            if (isStreaming) {
                if (currentStreamingMessage && currentStreamingMessage.classList.contains('streaming')) {
                    // 追加到现有流式消息
                    const contentSpan = currentStreamingMessage.querySelector('.message-content');
                    if (contentSpan) {
                        contentSpan.textContent += content;
                    } else {
                        currentStreamingMessage.textContent += content;
                    }
                    messagesDiv.scrollTop = messagesDiv.scrollHeight;
                    return;
                } else {
                    // 创建新的流式消息
                    const messageDiv = document.createElement('div');
                    messageDiv.className = `message ${type} streaming`;
                    messageDiv.innerHTML = `<span class="message-content">${content}</span>`;
                    messagesDiv.appendChild(messageDiv);
                    currentStreamingMessage = messageDiv;
                    messagesDiv.scrollTop = messagesDiv.scrollHeight;
                    return;
                }
            } else {
                // 完成流式消息
                if (currentStreamingMessage) {
                    currentStreamingMessage.classList.remove('streaming');
                    currentStreamingMessage = null;
                }
            }
            
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            
            // 处理确认消息
            if (type === 'confirmation' && data) {
                const options = data.options || ['确认', '取消'];
                messageDiv.innerHTML = `
                    <div><strong>需要确认：</strong>${data.message}</div>
                    <div class="confirmation-options">
                        ${options.map((option, index) => 
                            `<div class="confirmation-option" onclick="sendConfirmation('${data.confirmation_id}', '${option}')">
                                ${option}
                            </div>`
                        ).join('')}
                    </div>
                `;
            }
            // 处理工作流状态消息
            else if (type === 'workflow') {
                messageDiv.className = 'workflow-status';
                messageDiv.textContent = content;
            }
            // 处理Agent步骤消息
            else if (type === 'agent_step') {
                messageDiv.className = 'agent-step';
                messageDiv.textContent = content;
            }
            else {
                messageDiv.textContent = content;
            }
            
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        function sendConfirmation(confirmationId, selectedOption) {
            if (ws && ws.readyState === WebSocket.OPEN) {
                const message = {
                    type: 'confirmation_response',
                    confirmation_id: confirmationId,
                    response: selectedOption
                };
                ws.send(JSON.stringify(message));
                
                // 显示用户选择
                addMessage(`已选择：${selectedOption}`, 'user');
            }
        }
        
        function handleMessage(message) {
            console.log('收到消息:', message);
            
            switch (message.type) {
                case 'assistant':
                    const isStreaming = message.data.streaming || false;
                    addMessage(message.data.content, 'assistant', isStreaming);
                    break;
                case 'assistant_stream':
                    addMessage(message.data.content, 'assistant', true);
                    break;
                case 'assistant_complete':
                    // 完成流式消息
                    addMessage('', 'assistant', false);
                    break;
                case 'status':
                    addMessage(`[状态] ${message.data.message}`, 'system');
                    break;
                case 'error':
                    addMessage(`[错误] ${message.data.error_message}`, 'error');
                    break;
                case 'confirmation':
                    // 使用新的确认UI
                    addMessage('', 'confirmation', false, message.data);
                    break;
                case 'workflow_status':
                    addMessage(message.data.content || message.data.message, 'workflow');
                    break;
                case 'agent_step':
                    addMessage(message.data.content || message.data.message, 'agent_step');
                    break;
                case 'chart':
                    addMessage('[图表数据已生成]', 'system');
                    if (message.data.analysis_text) {
                        addMessage(message.data.analysis_text, 'assistant');
                    }
                    break;
                case 'form':
                    addMessage('[表单已创建]', 'system');
                    if (message.data.description) {
                        addMessage(message.data.description, 'assistant');
                    }
                    break;
                case 'heartbeat':
                    // 心跳消息不显示
                    break;
                default:
                    console.log('未处理的消息类型:', message.type);
            }
        }
        
        let selectedSkill = null;
        
        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message || !isConnected) {
                return;
            }
            
            // 显示用户消息
            let displayMessage = message;
            if (selectedSkill) {
                displayMessage = `[${selectedSkill}] ${message}`;
            }
            addMessage(displayMessage, 'user');
            
            // 发送到服务器
            const messageData = {
                type: 'user',
                data: {
                    content: message,
                    timestamp: new Date().toISOString(),
                    skill_selected: selectedSkill,
                    enable_network: false
                }
            };
            
            ws.send(JSON.stringify(messageData));
            
            // 清空输入框和选中的技能
            input.value = '';
            selectedSkill = null;
            updateSkillButtons();
        }
        
        function selectSkill(skillName) {
            if (!isConnected) {
                addMessage('[错误] 请先连接到服务器', 'error');
                return;
            }
            
            selectedSkill = skillName;
            updateSkillButtons();
            addMessage(`已选择技能: ${skillName}，请输入您的问题`, 'system');
        }
        
        function tryExample(skillName, exampleText) {
            if (!isConnected) {
                addMessage('[错误] 请先连接到服务器', 'error');
                return;
            }
            
            // 选择技能
            selectedSkill = skillName;
            updateSkillButtons();
            
            // 设置输入框内容
            const input = document.getElementById('messageInput');
            input.value = exampleText;
            
            // 显示选择的技能和示例
            addMessage(`已选择技能: ${skillName}，示例问题已填入`, 'system');
            
            // 聚焦到输入框
            input.focus();
        }
        
        function updateSkillButtons() {
            const buttons = document.querySelectorAll('.skill-button');
            buttons.forEach(button => {
                if (selectedSkill && button.onclick.toString().includes(selectedSkill)) {
                    button.classList.add('selected');
                } else {
                    button.classList.remove('selected');
                }
            });
        }
        
        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }
        
        // 启动心跳
        function startHeartbeat() {
            setInterval(() => {
                if (isConnected && ws) {
                    ws.send(JSON.stringify({
                        type: 'heartbeat',
                        data: {
                            timestamp: new Date().toISOString()
                        }
                    }));
                }
            }, 30000); // 每30秒发送一次心跳
        }
        
        // 页面加载完成后连接
        window.onload = function() {
            connect();
            startHeartbeat();
        };
    </script>
</body>
</html>
    """
    return html_content

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    """WebSocket端点"""
    await websocket.accept()
    session_id = str(uuid.uuid4())
    
    try:
        # 注册连接
        await ws_server.register_connection(websocket, session_id)
        
        while True:
            # 接收消息
            data = await websocket.receive_text()
            message_data = json.loads(data)
            
            # 处理消息
            await ws_server.handle_message(session_id, message_data)
            
    except WebSocketDisconnect:
        logger.info(f"客户端断开连接: {session_id}")
    except Exception as e:
        logger.error(f"WebSocket连接异常: {session_id}, {e}")
    finally:
        # 清理连接
        await ws_server.unregister_connection(session_id)

@app.get("/api/health")
async def health_check():
    """健康检查接口"""
    return {
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "version": "1.0.0",
        "services": {
            "websocket": "running",
            "workflow_manager": "running",
            "data_sources": "running"
        }
    }

@app.get("/api/stats")
async def get_stats():
    """获取系统统计信息"""
    try:
        connection_stats = ws_server.get_connection_stats()
        workflow_stats = workflow_manager.get_workflow_stats()
        
        return {
            "timestamp": datetime.now().isoformat(),
            "connections": connection_stats,
            "workflows": workflow_stats,
            "agents": {
                "available_agents": get_available_agents(),
                "total_agents": len(AGENT_REGISTRY)
            }
        }
    except Exception as e:
        logger.error(f"获取统计信息失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")

@app.get("/api/agents")
async def get_agents():
    """获取可用Agent列表"""
    try:
        agents = []
        for agent_name in get_available_agents():
            agent_class = AGENT_REGISTRY.get(agent_name)
            if agent_class:
                agent_instance = agent_class()
                agents.append({
                    "name": agent_name,
                    "description": agent_instance.description,
                    "examples": agent_instance.config.examples,
                    "capabilities": agent_instance.config.capabilities
                })
        
        return {
            "agents": agents,
            "total": len(agents)
        }
    except Exception as e:
        logger.error(f"获取Agent列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取Agent列表失败: {str(e)}")

@app.get("/api/data-sources/users")
async def get_users(name: str = None):
    """获取用户列表"""
    try:
        if name:
            users = await data_source_service.search_users(name)
        else:
            users = await data_source_service.get_user_list()
        
        return {
            "users": users,
            "total": len(users)
        }
    except Exception as e:
        logger.error(f"获取用户列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取用户列表失败: {str(e)}")

@app.get("/api/data-sources/departments")
async def get_departments(name: str = None):
    """获取部门列表"""
    try:
        if name:
            departments = await data_source_service.search_departments(name)
        else:
            departments = await data_source_service.get_department_list()
        
        return {
            "departments": departments,
            "total": len(departments)
        }
    except Exception as e:
        logger.error(f"获取部门列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取部门列表失败: {str(e)}")

if __name__ == "__main__":
    # 解析命令行参数
    parser = argparse.ArgumentParser(description='启动小U智能助手Demo服务器')
    parser.add_argument('--host', default=settings.HOST, help='服务器主机地址')
    parser.add_argument('--port', type=int, default=settings.PORT, help='服务器端口')
    parser.add_argument('--debug', action='store_true', default=settings.DEBUG, help='调试模式')
    args = parser.parse_args()
    
    print("程序开始执行")
    logger.info("启动小U智能助手Demo服务器")
    print(f"配置信息: HOST={args.host}, PORT={args.port}, DEBUG={args.debug}")
    
    # 启动FastAPI服务器
    print("准备启动uvicorn服务器")
    uvicorn.run(
        "main:app",
        host=args.host,
        port=args.port,
        reload=False,
        log_level="info"
    )
    print("uvicorn服务器已退出")